<template>
  <div>
    <!-- 搜索 -->
    <el-form :model="queryParams" ref="queryRef" label-width="auto" :inline="true" class="stust">
      <el-form-item>
        <div>箱号</div>
        <MultipleBoxNumbersDialog v-model="queryParams.refNos" />
      </el-form-item>
      <el-form-item  prop="businessNo">
        <div>业务编号</div>
        <el-input v-model="queryParams.businessNo" clearable/>
      </el-form-item>  
      <el-form-item  prop="refType" style="width:150px">
        <div>业务类型</div>
        <el-select v-model="queryParams.refType" clearable style="width: 100%;" placeholder="请选择业务类型">
          <el-option v-for="item in dictList.refTypeList" :key="item.value" :label="item.label"/>
        </el-select>
      </el-form-item>
      <el-form-item  prop="writeOffStatus" style="width:150px">
        <div>状态</div>
        <el-select v-model="queryParams.writeOffStatus" clearable style="width: 100%;" placeholder="请选择状态">
            <el-option v-for="item in writeOffStatusList" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item  prop="feeCodes" style="width:150px">
        <div>费用名称</div>
        <el-select v-model="queryParams.feeCodes" multiple collapse-tags clearable style="width: 100%;"  placeholder="请选择费用名称">
          <el-option v-for="item in feeCodeList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item  prop="settlementCompanyName">
        <div>结算单位</div>
        <el-input v-model.trim="queryParams.settlementCompanyName" clearable />
      </el-form-item>
      <el-form-item>
        <el-button @click="resetFrome" style="margin-top: 30px">重置</el-button>
        <el-button type="primary" @click="getFilterData" style="margin-top: 30px">搜索</el-button>
      </el-form-item>
    </el-form>
    <div style="display: flex;justify-content: flex-end;">
      <el-tooltip effect="dark" content="此按钮可选择当前页及后续页所有账单" placement="left">
        <template v-if="isSelectAll">
            <el-button :icon="Finished" size="small" @click="slectAll" plain class="operatingArea">全选</el-button>
        </template>
        <template v-else>
            <el-button size="small" @click="deselectAll" plain class="operatingArea">取消全选</el-button>
        </template>
      </el-tooltip>
      <el-button type="primary" size="small" :icon="Upload"  @click="toExporFeeDetails">导出</el-button>
      <el-button type="primary" size="small" :icon="Plus"  @click="addPermissionRoleDialog">新建账单</el-button>
    </div>
    <div class="main-cent" >
      <!-- tabs切换 -->
      <!-- <el-tabs v-model="queryParams.settlementDirection" class="tabs" @tab-change="handleClick">
        <el-tab-pane v-for="item in tabsList" :key="item.value" :label="item.label" :name="item.value"></el-tab-pane>
      </el-tabs> -->
      <Table ref="tableRef" v-bind="tableData"  @pageChange="pageChange" @activeRemark="activeRemark" @updateSelectAll="updateSelectAll" :disableHeaderCheckbox="disableHeaderCheckbox"></Table>
    </div>
      <!-- 备注 -->
    <el-dialog v-model="rowData.dialogVisibleRemark" :title="rowData.remarksTitle" width="300">
      <div style="width: 100%;text-align: center;margin-top: 20px;">
        <el-input v-model="from.remarkValSync" type="textarea" show-word-limit maxlength="200" rows="2"></el-input>
      </div>
      <div style="width: 100%;text-align: center;margin-top: 40px;">
        <el-button type="primary" @click="handleRemark" plain style="width:100px">确定</el-button>
      </div>
    </el-dialog>
    <!-- 新增账单弹窗 -->
    <add-modal-form ref="addModalMormRef"  @addModal="getFilterData"></add-modal-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onActivated,computed,onMounted,inject } from 'vue'
import Table from '@/components/table'
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus,Gri,Upload,Finished } from '@element-plus/icons-vue'
import { getTableList, updateFeeDetailsRemark,exporFeeDetails,getFeeDetai} from '@/api/financial/operatingInfo'
import MultipleBoxNumbersDialog from '@/components/dialog/multipleBoxNumbersDialog.vue'
import AddModalForm from '@/views/financialManage/operatingInfo/components/addModalForm.vue'
import dictList from '@/utils/dictList'
import { downloadFile } from '@/utils/download'
const isAgent=inject('isAgent') //当前等角色  true 货代角色  false 集装箱公司角色
const formData = inject('formData')
const addModalMormRef = ref()
const queryRef=ref(null)
const dialogPitchUploadVisible = ref(false) //导入弹框
const isSelectAll = ref(true) // true:显示全选按钮  false：显示取消全选按钮
const tabsList=ref([
{ label: '应收', value: 1 },
{ label: '应付', value: -1},
])
const dateObj=ref({
  beginPlanPickupDate:null,
  beginReturnDate:null,
  beginCreateDate:null,
  beginSellDate:null
})
const data = reactive({
  queryParams: {
    refNos:'',
    refType:null,
    businessNo:'',
    settlementDirection:'',
    writeOffStatus:'',
    settlementCompanyName:'',
    settlementCompanyTypes:[5,15,20],
    feeCodes:[],
    orderId:'',
    pageNum: 1,
    pageSize: 10,
  },
  rowData:{
    dialogVisibleRemark:false,
    remarksTitle:'添加备注'

  },
  from:{
  }
});
const { queryParams,from,rowData } = toRefs(data);
const feeCodeList=ref([
  {
    value:5,
    label:'修箱费'
  },{
    value:10,
    label:'提箱费'
  },{
    value:15,
    label:'翻箱费'
  },{
    value:20,
    label:'其他费用'
  },{
    value:25,
    label:'超期费'
  },{
    value:30,
    label:'吊装费'
  },{
    value:35,
    label:'堆存超期费'
  },{
    value:40,
    label:'租入费'
  },{
    value:45,
    label:'租出费'
  },{
    value:50,
    label:'购箱费'
  },{
    value:55,
    label:'卖箱费'
  },{
    value:60,
    label:'箱贴费'
  },
])
const writeOffStatusList=ref([
  {
    value:5,
    label:'未建账单'
  },{
    value:10,
    label:'已建账单'
  },{
    value:15,
    label:'已对账'
  },
])
onMounted(() => {
  getFilterData()
})
// 基础数据
const tableData = reactive({
  header: [
    { key: 'businessNo', colWidth: '120', title: '业务编号', type: '<a>', isCheck: true ,},
    { key: 'refNo', colWidth: '150', title: '箱号',type: '<a>',isCheck: true },
    { key: 'refType', colWidth: '80', title: '业务类型', type: 'filter', filter: dictList.refTypeList1, isCheck: true },
    { key: 'feeCode', colWidth: '80', title: '费用名称', type: 'filter', filter: { 5: '修箱费', 10: '提箱费', 15: '翻箱费', 20: '其他费用', 25: '超期费' , 30: '吊装费' , 35: '堆存超期' , 40: '租入费' , 45: '租出费' , 50: '购箱费' , 55: '卖箱费' , 60: '箱贴费'  }, isCheck: true },
    { key: 'deductAmount',currency:"feeCurrency", colWidth: '100', title: '金额', type: 'add', isCheck: true },
    { key: 'settlementCompanyName', colWidth: '200', title: '结算单位', type: 'text', isCheck: true },
    {
      key: 'remark',
      colWidth: '200',
      title: '备注',
      type: 'remark',
      isCheck: true,
      buttons: [
        {
          icon: 'Plus',
          command: 'activeRemark',
          name: '添加备注',
          isShow: (row: any) => {
            return !row.remark;
          },
        },
        {
          icon: 'Edit',
          command: 'activeRemark',
          showOnlyKey: true,
          name: '编辑备注',
          isShow: (row: any) => {
            return row.remark;
          },
        },
      ],
    },
    { key: 'writeOffStatus', colWidth: '100', title: '状态', type: 'writeOffStatus', isCheck: true },
  ],
  data: [],
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 总条数
    loading: false,
    isRealName: false, // 是否已经实名认证
  },

})
const tableRef = ref({ multipleSelection: [] })
const selection = computed(() => {
  let ids: any[] = []
  tableRef.value.multipleSelection.map((item: any) => {
    ids.push(item.id)
  })
  return ids
})
//tabs切换 列表字段是否显示
const handleClick=()=>{
  tableRef.value.clearCheckAll()
  getFilterData()
  tableData.header.forEach((item)=>{
    if(queryParams.value.refType==20){
      if(item.key=='boxUsagePeriod'){
        item.isCheck=false
      }else if(item.key=='outDate'){
        item.isCheck=false

      }else if(item.key=='shouldReturnDate'){
        item.isCheck=false

      }else if(item.key=='returnDate'){
        item.isCheck=false

      }else if(item.key=='sellDate'){
        item.isCheck=true
      }
    }else{
      if(item.key=='boxUsagePeriod'){
        item.isCheck=true
      }else if(item.key=='outDate'){
        item.isCheck=true
      }else if(item.key=='shouldReturnDate'){
        item.isCheck=true
      }else if(item.key=='returnDate'){
        item.isCheck=true
      }else if(item.key=='sellDate'){
        item.isCheck=false
      }
    }
  })
  // tableData.header[0].refType=true
}
const activeRemark = (row: any) => {
  console.log('row',row)
  // rowData.value = row;
  // console.log("activeRemark",row)
  rowData.value.dialogVisibleRemark = true;
  from.value.remarkValSync = row.remark;
   from.value.id = row.id;
  if (row.remark) {
    rowData.value.remarksTitle = '编辑备注'
  } else {
    rowData.value.remarksTitle = '添加备注'
  }
};
//添加|修改备注
const handleRemark = (row: any) => {
  const data = { id: from.value.id, "remark": from.value.remarkValSync }
  updateFeeDetailsRemark(data).then((res: any) => {
    ElMessage.success('备注修改成功');
    rowData.value.dialogVisibleRemark = false;
    getFilterData()
  })
};
// 重置搜索数据
const resetFrome = () => {
  queryRef.value.resetFields()
  queryParams.value.refNos=''
  getFilterData()
}
const reqParams = ref({})
// 搜索数据
const getFilterData = () => {
  if (dateObj.value.beginPlanPickupDate) {
    queryParams.value.beginPlanPickupDate = dateObj.value.beginPlanPickupDate[0]
    queryParams.value.endPlanPickupDate = dateObj.value.beginPlanPickupDate[1]
  }
  if (dateObj.value.beginReturnDate) {
    queryParams.value.beginReturnDate = dateObj.value.beginReturnDate[0]
    queryParams.value.endReturnDate = dateObj.value.beginReturnDate[1]
  }
  if (dateObj.value.beginCreateDate) {
    queryParams.value.beginCreateDate = dateObj.value.beginCreateDate[0]
    queryParams.value.endCreateDate = dateObj.value.beginCreateDate[1]
  }
  if (dateObj.value.beginSellDate) {
    queryParams.value.beginSellDate = dateObj.value.beginSellDate[0]
    queryParams.value.endSellDate = dateObj.value.beginSellDate[1]
  }
  let queryData = JSON.parse(JSON.stringify(queryParams.value))
  if(queryData.refNos && queryData.refNos!=''){
    queryData.refNos=queryParams.value.refNos.split(',')
  }else{
   delete queryData.refNos
  }
queryData.orderId=formData.value.id
  reqParams.value = {}
  reqParams.value = queryData
  getFeeDetai(queryData).then(res => {
    tableData.data = res.data.list.sort((a, b) => a.sort - b.sort)
    tableData.config.total = res.data.total
    console.log(res)
  })
}

// 新增账单
const addPermissionRoleDialog = () => {
  let row = selection.value
    if(row.length==0){
      ElMessage.warning('请选择费用明细');
        return false
    }
  let billStatusIn=false
    //已建账单不能新建账单
    tableData.data.map(item=>{
      row.map(itemInfo=>{
        if(item.id==itemInfo){
           if(item.writeOffStatus==10){
              billStatusIn=true
            }
        }
      })
    })
    if(billStatusIn){
        ElMessage.warning('请选择未建的账单');
        return false
    }

  addModalMormRef.value.onShow(row,1,queryParams.value.settlementDirection)
}

// // 编辑
// const editPermissions = (row) => {
//   updateModalMormRef.value.onShow(row.id,1)
// }
// // 查看
// const examine = (row) => {
//   updateModalMormRef.value.onShow(row.id,2)
// }
// // 查看单票利润
// const examineMode = (row) => {
//   examineModalMormRef.value.onShow(row.id,row.refType)
// }

// 批量操作
// const batchTap= (type) => {
//   //type  1导入  2编辑  3删除
//   if(type==1){
//     dialogPitchUploadVisible.value=true
//   }else if(type==2){
//     let row=selection.value
//     if(row.length==0){
//       ElMessage.warning('请选择编辑的数据');
//         return false
//     }
//     feetModalMormRef.value.onShow(row,queryParams.value.refType)
//   }else if(type==3){
//     let row=selection.value
//     if(row.length==0){
//       ElMessage.warning('请选择删除的数据');
//         return false
//     }
//     deleteBox(row)
//   }
// }

const toExporFeeDetails = () => { 
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }

  const ids = checkAllItem.map((item: any) => item.id)

  ElMessageBox.confirm('确认要导出选中的账单', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      let reqParameters = {
        feeDetailsIds: ids
        }
        exporFeeDetails(reqParameters).then((res: any) => {
            downloadFile(res, '费用明细') 
        }).catch((error) => {
            ElMessage.error(error)
        })
    }).catch(() => { });
}



const allId = ref([]) // 使用全选功能时使用
const isAllCheck = ref(false) //是否使用全选功能
const checkAll = ref([]) //点击全选按钮时 选中列表所有内容（包含当前页和所有后续页）

const disableHeaderCheckbox = ref(false) // true:禁用表头全选/全取消 选择框 false:开启 表头全选/全取消 选择框
const slectAll = async(val:any) =>{
    checkAll.value = []
    reqParams.value.pageSize = 100000
    await getTableList(reqParams.value).then(res =>{ 
      if(res.code == "00000" && res.data.list && res.data.total){
        isSelectAll.value = false
        disableHeaderCheckbox.value = true
        res.data.list.forEach(item => {
          checkAll.value.push(item)
        })
        isAllCheck.value = true
        allId.value = checkAll.value
        tableRef.value.checkAll()
      }else{
        ElMessage.error("全选失败，请刷新页面，或者手动选择")
      }
 })
}

const deselectAll = () =>{
  allId.value = []
  disableHeaderCheckbox.value = false
  tableRef.value.clearCheckAll()
  isSelectAll.value = true
}

const updateSelectAll = (val) => {
  allId.value = val
  // console.log("11111",allId.value)
}

// // 翻页控制
const pageChange = (val) => {
  queryParams.value.pageNum=val.pageNum
  queryParams.value.pageSize=val.pageSize
  getFilterData()
}

</script>

<style scoped>
.choose-item-2 {
  margin-left: 20px;
}
.stust{
  padding:0 20px;
  margin-bottom: 30px;
}
.choose-item-3 {
  display: block;
  margin-left: 20px;
}
.main-cent{
  padding: 0 10px;
}
.header-title{
  border-left: 4px solid #2158F3;
  padding-left: 8px;
  line-height: 18px;
}
.tabs{
  width: 10%;
}
</style>